
using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.AutoMapper;
using Abp.Linq.Extensions;
using Abp.Extensions;
using Abp.Domain.Repositories;
using L._52ABP.Application.Dtos;
using L._52ABP.Common.Extensions.Enums;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using LTMCompanyName.YoyoCmsTemplate.Exam;
using LTMCompanyName.YoyoCmsTemplate.Exam.Dtos;
using LTMCompanyName.YoyoCmsTemplate.Exam.DomainService;
using LTMCompanyName.YoyoCmsTemplate.Authorization;
using LTMCompanyName.YoyoCmsTemplate.Exam.Colleges.Enum;
using LTMCompanyName.YoyoCmsTemplate.Enums;

namespace LTMCompanyName.YoyoCmsTemplate.Exam
{
    /// <summary>
    /// 应用层服务的接口实现方法
	/// <see cref="College" />
    ///</summary>

    public class CollegeAppService : YoyoCmsTemplateAppServiceBase, ICollegeAppService
    {



        private readonly ICollegeManager _collegeManager;
        private readonly IRepository<College, long> _entityRepository;
        private readonly IRepository<StockCategory, long> _stockCategoryRepository;
        private readonly IStockCategoryAppService _stockCategoryAppService;

        /// <summary>
        /// 构造函数
        ///</summary>

        public CollegeAppService(ICollegeManager collegeManager, IRepository<College, long> entityRepository, IStockCategoryAppService stockCategoryAppService, IRepository<StockCategory, long> stockCategoryRepository)
        {
            this._collegeManager = collegeManager;
            this._entityRepository = entityRepository;
            this._stockCategoryAppService = stockCategoryAppService;
            this._stockCategoryRepository = stockCategoryRepository;
        }


        /// <summary>
        /// 获取的分页列表信息
        ///</summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(CollegePermissions.College_Query)]
        public async Task<PagedResultDto<CollegeListDto>> GetPaged(GetCollegesInput input)
        {
            //当前用户id
            var query = this._entityRepository.GetAll().AsNoTracking().WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.Name.Contains(input.FilterText)).Where(a => a.CreatorUserId == AbpSession.UserId);
            // TODO:根据传入的参数添加过滤条件

            var count = await query.CountAsync();

            var collegeList = await query
            .OrderBy(input.Sorting).AsNoTracking()
            .PageBy(input)
            .ToListAsync();
            // 包装列表需要显示的字段
            var collegeListDtos = collegeList.Select(item =>
            {
                return new CollegeListDto
                {
                    Id = item.Id,
                    Name = item.Name,
                    Sort = item.Sort,
                    Status = item.Status,
                    StatusName = ((Status)Convert.ToInt32(item.Status)).GetDescription(),
                };
            }).ToList();
            return new PagedResultDto<CollegeListDto>(count, collegeListDtos);
        }

        /// <summary>
        /// 获取学院
        ///</summary>
        /// <returns></returns>
        public async Task<PagedResultDto<CollegeListDto>> Get()
        {
            //当前用户id
            var query = this._entityRepository.GetAll().OrderBy(x => x.Sort).Where(x=>x.Status=="1");
            // TODO:根据传入的参数添加过滤条件

            var count = await query.CountAsync();

            var collegeList = await query.ToListAsync();
            // 包装列表需要显示的字段
            var collegeListDtos = collegeList.Select(item =>
            {
                return new CollegeListDto
                {
                    Id = item.Id,
                    Name = item.Name,
                    Sort = item.Sort,
                    Status = item.Status,
                    StatusName = ((Status)Convert.ToInt32(item.Status)).GetDescription(),
                };
            }).ToList();
            return new PagedResultDto<CollegeListDto>(count, collegeListDtos);
        }


        /// <summary>
        /// 通过指定id获取CollegeListDto信息
        /// </summary>
        [AbpAuthorize(CollegePermissions.College_Query)]
        public async Task<CollegeListDto> GetById(EntityDto<long> input)
        {
            var entity = await _entityRepository.GetAsync(input.Id);

            var dto = ObjectMapper.Map<CollegeListDto>(entity);
            return dto;
        }

        /// <summary>
        /// 获取编辑 
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(CollegePermissions.College_Create, CollegePermissions.College_Edit)]
        public async Task<GetCollegeForEditOutput> GetForEdit(NullableIdDto<long> input)
        {
            var output = new GetCollegeForEditOutput();
            CollegeEditDto editDto;

            if (input.Id.HasValue)
            {
                var entity = await _entityRepository.GetAsync(input.Id.Value);
                editDto = ObjectMapper.Map<CollegeEditDto>(entity);
            }
            else
            {
                editDto = new CollegeEditDto();
            }
            output.College = editDto;
            return output;
        }


        /// <summary>
        /// 添加或者修改的公共方法
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(CollegePermissions.College_Create, CollegePermissions.College_Edit)]
        public async Task CreateOrUpdate(CreateOrUpdateCollegeInput input)
        {

            if (input.College.Id.HasValue)
            {
                await Update(input.College);
            }
            else
            {
                await Create(input.College);
            }
        }


        /// <summary>
        /// 新增
        /// </summary>
        [AbpAuthorize(CollegePermissions.College_Create)]
        protected virtual async Task<CollegeEditDto> Create(CollegeEditDto input)
        {
            //TODO:新增前的逻辑判断，是否允许新增

            var entity = ObjectMapper.Map<College>(input);
            //调用领域服务
            entity = await _entityRepository.InsertAsync(entity);

            var dto = ObjectMapper.Map<CollegeEditDto>(entity);
            return dto;
        }

        /// <summary>
        /// 编辑
        /// </summary>
        [AbpAuthorize(CollegePermissions.College_Edit)]
        protected virtual async Task Update(CollegeEditDto input)
        {
            //TODO:更新前的逻辑判断，是否允许更新

            var entity = await _entityRepository.GetAsync(input.Id.Value);
            //  input.MapTo(entity);
            //将input属性的值赋值到entity中
            ObjectMapper.Map(input, entity);
            await _entityRepository.UpdateAsync(entity);
        }



        /// <summary>
        /// 删除信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(CollegePermissions.College_Delete)]
        public async Task Delete(EntityDto<long> input)
        {
            //关联题库分类删除
            var idList = this._stockCategoryRepository.GetAll().Where(a => input.Id==a.CollegeId).Select(x => x.Id).ToList();
            if (idList != null)
            {
                await this._stockCategoryAppService.BatchDelete(idList);
            }
            //TODO:删除前的逻辑判断，是否允许删除
            await _entityRepository.DeleteAsync(input.Id);
        }



        /// <summary>
        /// 批量删除College的方法
        /// </summary>
        [AbpAuthorize(CollegePermissions.College_BatchDelete)]
        public async Task BatchDelete(List<long> input)
        {
            //关联题库分类删除
            var idList = this._stockCategoryRepository.GetAll().Where(a => input.Contains(a.CollegeId)).Select(x=>x.Id).ToList();
            if (idList != null)
            {
                await this._stockCategoryAppService.BatchDelete(idList);
            }
            // TODO:批量删除前的逻辑判断，是否允许删除
            await this._entityRepository.DeleteAsync(a => input.Contains(a.Id));
        }
    }
}


